// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Linq;
using System.Xml.Linq;

namespace SnapObjects.Data
{
    internal class XmlTemplateImportSchemaParser : ITemplateImportSchemaParser
    {
        private ITemplateImportProvider _provider;

        private readonly TemplateImportSchema _schema;

        public XmlTemplateImportSchemaParser()
        {
            _schema = new TemplateImportSchema();
        }

        public TemplateImportSchema Parse(string template, ITemplateImportProvider provider)
        {
            _provider = provider;

            var document = XDocument.Parse(template);

            this.Parse(document.Root);

            if (_schema.Nodes.Count == 0)
            {
                throw new Exception(Properties.Resource.TEMPLATEIMPORT_TYPENOTMATCH_EXCEPTION);
            }

            return _schema;
        }

        private void Parse(XElement element)
        {
            foreach (var item in element.Elements())
            {
                if (item.HasElements)
                {
                    this.Parse(item);
                }
                else if (!_schema.Nodes.ContainsKey(item.Name.LocalName))
                {
                    var column = _provider.GetColumns().FirstOrDefault
                    (
                        x => x.Key.Equals(item.Name.LocalName, StringComparison.OrdinalIgnoreCase)
                    );

                    if (column.Key != null)
                    {
                        var node = new TemplateImportShcemaNode(column.Key, column.Value);

                        _schema.Nodes.Add(item.Name.LocalName, node);
                    }
                }
            }
        }
    }
}
